package com.easy.web.controller;

import com.easy.web.model.User;
import com.easy.web.model.UserLevel;
import com.easy.web.service.UserService;
import com.easy.web.utils.EasyConstant;
import com.easy.web.utils.MD5Util;
import com.easy.web.utils.SystemUtils;
import com.easy.web.utils.ViewUtils;
import com.easy.web.vo.UserVo;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by 郏高阳 on 2017/2/28.
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping(value = "login_time_out", method = {RequestMethod.GET})
    public ModelAndView login_time_out() {
        return new ModelAndView("", ViewUtils.mapFail("403","登录超时,请重新登陆"));
    }



    /**
     * 新增注册用户
     */
    @RequestMapping(value = "register", method = {RequestMethod.POST})
    public ModelAndView register(String userName, String password, String phoneNum, String code, String QQ,String email,HttpServletRequest request) {
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setName(userName);
        user.setNickname(userName);
        user.setPassword(MD5Util.md5(password));
        user.setPhone(phoneNum);
        user.setQq(QQ);
        user.setLevel(EasyConstant.DEF_USER_LEVEL);
        user.setEmail(email);
        user.setIsActive(EasyConstant.YES_STR);
        user.setCreateTime(new Date());
//        user.setIsAuditor(EasyConstant);
        String ipAddress = SystemUtils.getRemortIP(request);
        user.setIpAddress(ipAddress);
        //归属地
        String locationAddress=SystemUtils.getIPLocationAddress(ipAddress);
        user.setAttribution(locationAddress);
//        Sms sms=smsService.querySmsByPhoneNumber(phoneNum);
//        if(sms == null){
//            return new ModelAndView("", ViewUtils.mapFail("验证码不正确"));
//        }
//        if(!code.equals(sms.getCode())){
//            return new ModelAndView("", ViewUtils.mapFail("验证码不正确"));
//        }
        try {
            userService.addUser(user);
        } catch (DuplicateKeyException e) {
            return new ModelAndView("", ViewUtils.mapFail("用户已经存在，请重新注册"));
        }
        return new ModelAndView("", ViewUtils.mapSuccess("success"));
    }
    /**
     * 管理员添加用户
     */
    @RequestMapping(value = "registerByAdmin", method = {RequestMethod.POST})
    public ModelAndView registerByAdmin(@RequestParam(value = "userName",required = true) String userName,
                                        @RequestParam(value = "password",required = true) String password,
                                        @RequestParam(value = "phoneNum",required = true) String phoneNum,
                                        @RequestParam(value = "QQ") String QQ,
                                        @RequestParam(value = "level") String level,
                                        HttpServletRequest request) {
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setName(userName);
        user.setNickname(userName);
        user.setPassword(MD5Util.md5(password));
        user.setPhone(phoneNum);
        user.setQq(QQ);
        UserLevel userLevel = userService.getLevelInfo(level);
        if (userLevel != null) {
            user.setLevel(userLevel.getId());
        } else {
            return new ModelAndView("", ViewUtils.mapFail("用户等级异常"));
        }
//        user.setEmail(email);
        user.setIsActive(EasyConstant.YES_STR);
        user.setCreateTime(new Date());
//        user.setIsAuditor(isAuditor);
//        //用户ip
//        String ipAddress = SystemUtils.getRemortIP(request);
//        user.setIpAddress(ipAddress);
//        //归属地
//        String locationAddress = SystemUtils.getIPLocationAddress(ipAddress);
//        user.setAttribution(locationAddress);
        try {
            userService.addUser(user);
        } catch (DuplicateKeyException e) {
            return new ModelAndView("", ViewUtils.mapFail("用户已经存在"));
        }
//        user.setLevel(level);
        return new ModelAndView("", ViewUtils.mapSuccess("success"));
    }
    /**
     * 用户登录
     */
    @RequestMapping(value = "login", method = {RequestMethod.GET})
    public ModelAndView login(@RequestParam(value = "userName", required = true) String userName,
                              @RequestParam(value = "password", required = true) String password,
                              HttpServletRequest request) {
        User user = null;
        try {
            user = userService.queryUserByUserName(userName);
        } catch (Exception e) {
            return new ModelAndView("", ViewUtils.mapFail("用户登陆失败"));
        }
        if (user == null) {
            return new ModelAndView("", ViewUtils.mapFail("该用户不存在"));
        } else if (!user.getPassword().equals(MD5Util.md5(password))) {
            return new ModelAndView("", ViewUtils.mapFail("密码错误，请重新输入"));
        }
        UserVo userVo = new UserVo(user);
        userVo.setUserLevel(userService.queryUserLevelByLevelId(userVo.getLevel()));
        // 将用户信息保存到session中
        request.getSession().setAttribute("userVo", userVo);
        return new ModelAndView("", ViewUtils.mapSuccess(user));
    }


    /**
     * 用户修改密码
     *
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "updatePassWord", method = {RequestMethod.POST})
    public ModelAndView updateUsrPassWord(@RequestParam(value = "password", required = true) String password, HttpServletRequest request) {

        UserVo userVo = (UserVo) request.getSession().getAttribute("userVo");
        User user = new User();
        user.setId(userVo.getId());
        user.setPassword(MD5Util.md5(password));

        try {
            userService.updateUser(user);
        } catch (Exception e) {
            return new ModelAndView("", ViewUtils.mapFail("修改密码失败"));
        }

        return new ModelAndView("", ViewUtils.mapSuccess(user));
    }

    /**
     * 注销
     * @param request
     * @return
     */
    @RequestMapping(value = "logout",method = {RequestMethod.GET})
    public ModelAndView logout(HttpServletRequest request){
        request.getSession().removeAttribute("userVo");
        return new ModelAndView("", ViewUtils.mapSuccess("success"));
    };

    /**
     * 查询用户
     */
    @RequestMapping(value = "getUseInfo", method = {RequestMethod.POST})
    public ModelAndView getUseInfo(String searchValue){
        List<User> users = userService.getUserListByLike(JSONObject.fromObject(searchValue));
        for (User user:users){
            UserLevel userLevel = userService.queryUserLevelByLevelId(user.getLevel());
            user.setLevel(userLevel.getName());
        }
        return new ModelAndView("",ViewUtils.mapSuccess(users));
    }

    /**
     * 删除某个用户
     */
    @RequestMapping(value = "delUser", method = {RequestMethod.POST})
    public ModelAndView delUser(@RequestParam(value = "id",required = true) String id){
        userService.delUser(id);
        return new ModelAndView("",ViewUtils.mapSuccess("success"));
    }

    /**
     *  查询用户列表
     * @return
     */

    @RequestMapping(value = "showUserList", method = {RequestMethod.GET})
    public ModelAndView showUserList(int number){

        List<User> users =getUserList();
        Map<String,Object> result=new HashMap<>();
        result.put("userList",users);
        result.put("totalPage",users.size()/number);
        return new ModelAndView("",ViewUtils.mapSuccess(result));
    }

    public List<User> getUserList(){
        List<User> users =userService.getUserList();

        for (User user:users){
            UserLevel userLevel = userService.queryUserLevelByLevelId(user.getLevel());
            user.setLevel(userLevel.getName());
        }
        return  users;
    }



    /**
     * 查询用户等级
     */
    @RequestMapping(value = "getUseLevel", method = {RequestMethod.GET})
    public ModelAndView getUseLevel(){

        List<UserLevel> userLevels = userService.queryAllUserLevel();
//        List<String> strings=userLevels.parallelStream().map(UserLevel::getName).collect(Collectors.toList());
        return new ModelAndView("",ViewUtils.mapSuccess(userLevels));
    }

    /**
     * 用户更新资料
     */
    @RequestMapping(value = "updateUserInfo", method = {RequestMethod.POST})
    public ModelAndView updateUserInfo(String userName, String email, String password, HttpServletRequest request){
        UserVo userVo = (UserVo) request.getSession().getAttribute("userVo");

        if (userVo == null) {
            return new ModelAndView("", ViewUtils.mapFail("登陆超时，请重新等录"));
        }

        //TODO  修改用户资料
        userService.updateUser(userVo);

        return new ModelAndView("",ViewUtils.mapSuccess("success"));
    }

    /**
     *  调整用户等级权限
     */

    @RequestMapping(value = "updateUserLevel", method = {RequestMethod.POST})
    public ModelAndView updateUserLevel(@RequestParam(value = "id",required = true) String id,
                                        @RequestParam(value = "level",required = false) String level){
        User user =userService.queryUserById(id);
        if(user == null){
            return new ModelAndView("", ViewUtils.mapFail("无法查到该用户信息！"));
        }else{
            if(StringUtils.isBlank(level)){
                return new ModelAndView("", ViewUtils.mapFail("用户等级不允许为空"));
            }
            UserLevel userLevel =userService.getLevelInfo(level);
            if(userLevel!=null){
                user.setLevel(userLevel.getId());
            }
            userService.updateUser(user);
        }

        return new ModelAndView("",ViewUtils.mapSuccess("success"));
    }

}
